const publishBtn=document.querySelector('.top-publish-btn')
const publishBox=document.querySelector('.publishBlogBox')
const publish=document.querySelector('.publish')
const publishCancel=document.querySelector('.publishCancel')
const categorySelects=document.querySelector('#categorySelects')
const imagePreviewContainer=document.querySelector('.imagePreviewContainer')
const labelListUl=document.querySelector('.labelListUl')

$.ajax({
    url: "/weibo/blog/getTypeByLike",
    type: "post",
    success: function (result) {
        console.log(result)
        result.forEach(function(category){
            categorySelects.innerHTML+='<div class="checkboxDiv"><input type="checkbox" onchange="checkBoxChange()" name="type" value="' + category + '"> '+ '<i>'+category+'</i></div>'
        });
    },
    error: function (error) {
        console.log('失败')
    },
});

function checkBoxChange(){
    // 获取所有的checkbox

    let checkedCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
    let checkboxes = document.querySelectorAll('input[type="checkbox"]');

    console.log(checkedCount)
    if(checkedCount === 5){
        checkboxes.forEach(function(checkbox) {
            if (!checkbox.checked) {
                checkbox.disabled = true;
            }
        });
    }else{
        checkboxes.forEach(function(checkbox) {
                checkbox.disabled = false;
        });
    }
}
publishBtn.addEventListener('click',()=>{
    publishBox.classList.remove('hidden')
    document.body.style.overflow="hidden"
})
publishCancel.addEventListener('click',()=>{
    publishBox.classList.add('hidden')
    document.body.style.overflow="visible"
})

let imageFiles = []; // 用于存储用户选择的图片文件
let imageInput = document.getElementById('imageInput');
imageInput.addEventListener('change', function() {
    let files = Array.from(imageInput.files);
    imageFiles = imageFiles.concat(files);
    imageInput.value = ''; // 清空input的值
    updateImagePreview();
});
document.querySelector('.addImageButton').addEventListener('click', function() {
    if(imageFiles.length<9){
        imageInput.click();
    }else{
        showCustomAlert('最多添加9张图片',false)
    }
});
//更新图片的预览
function updateImagePreview() {
    imagePreviewContainer.innerHTML = ''; // 清空现有的预览内容

    imageFiles.forEach(function(file, index) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const img = document.createElement('img');
            img.src = e.target.result;
            img.classList.add('previewImage');

            const closeButton = document.createElement('button');
            closeButton.innerHTML ='&times;'
            closeButton.classList.add('closePreviewImage')
            closeButton.addEventListener('click', function() {
                // 移除对应的图片预览和关闭按钮
                previewContainer.remove();
                // 从imageFiles数组中移除对应的文件
                imageFiles.splice(index, 1);
            });

            const previewContainer = document.createElement('div');
            previewContainer.appendChild(img);
            previewContainer.appendChild(closeButton);

            imagePreviewContainer.appendChild(previewContainer);
        };
        reader.readAsDataURL(file);
    });
}

const blogPubForm=document.querySelector('.blogPubForm')
blogPubForm.addEventListener('submit',function(e){
    e.preventDefault()
    if (imageFiles.length==0&& setText(blogPubForm.text.value)==''){
        showCustomAlert('请输入文本或添加图片内容')
        return
    }
    const formData = new FormData();
    imageFiles.forEach(file => {
        formData.append('myFiles', file);
    });
// 添加其他数据到FormData对象
    formData.append('label', setText(blogPubForm.label.value));
    formData.append('text', setText(blogPubForm.text.value));
    const selectedTypes = Array.from(document.querySelectorAll('input[type="checkbox"]:checked')).map(checkbox => checkbox.value);
    selectedTypes.forEach(type => {
        formData.append('type', type);
    });
// 将FormData对象添加到ajax请求的data字段中
    $.ajax({
        url: "/weibo/blog/addBlog",
        type: "post",
        data: formData,
        processData: false,
        contentType: false,
        success: function (result) {
            showCustomAlert('发布成功',true)
        },
        error: function (error) {
            showCustomAlert('发布失败',false)
        },
    });
})
let labelList = document.querySelector(".labelList");
let labelInput = document.querySelector("#label");
labelInput.addEventListener("focus", function() {
    labelList.style.display = "block";
});
labelInput.addEventListener("blur", function() {
    setTimeout(function() {
        labelList.style.display = "none";
    }, 200); // 延迟隐藏 labelList
});
function searchLabel() {
    let labelInputValue=labelInput.value
    $.ajax({
        url: "/weibo/blog/getLabelByLike",
        type: "post",
        data: {
            condition:labelInputValue
        },
        success: function (result) {
            labelListUl.innerHTML=''
            result.forEach(function(label) {
                let li = document.createElement('li');
                li.textContent = label; // Assuming label is a string
                labelListUl.appendChild(li);
                labelListUl.addEventListener('click', function(event) {
                    if (event.target.tagName === 'LI') {
                        labelInput.value = event.target.textContent;
                    }
                });
            });
        },
        error: function (error) {
            console.log(error)
        },
    });
}

labelInput.addEventListener("input", debounce(searchLabel, 300));

